package com.test.demo.javabasis.mutithread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierAndCountDownDemo {

    public static void main(String[] args) throws InterruptedException {
        cyclicBarrier();
        countDown();
        System.out.println("main");
    }

    public static void cyclicBarrier(){
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2,()->{
            System.out.println("cyclicBarrier ???  ");
        });
        new Thread(()->{
            try {
                System.out.println("1");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                System.out.println("2");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public static void countDown() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(()->{
            try {
                System.out.println("1");
                countDownLatch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                System.out.println("2");
                countDownLatch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        countDownLatch.await();
        System.out.println("countDownLatch   ???");
    }
}
